package com.fulihui.wgj.admin.security.jwt;

import com.fulihui.wgj.admin.config.properties.JwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: Levon
 * @version: v 0.1 2018-06-14 16:34
 */
@Configuration
public class JwtHelper {

    static JwtProperties jwtProperties;

    public final static String LOGIN_ID = "LOGIN_ID";

    public final static String PLATFORM_APP_ID = "PLATFORM_APP_ID";

    @Autowired
    public JwtHelper(JwtProperties jwtProperties) {
        JwtHelper.jwtProperties = jwtProperties;
    }

    /**
     * 解析jwt
     *
     * @param jsonWebToken
     * @param base64Security
     * @return
     */
    public static Claims parseJWT(String jsonWebToken, String base64Security) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(base64Security))
                    .parseClaimsJws(jsonWebToken).getBody();
            return claims;
        } catch (Exception ex) {
            return null;
        }
    }


    public static String createJWT(Map<String, Object> params, String audience, String issuer, long TTLMillis, String base64Security) {

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        //生成签名密钥
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                .setClaims(params)
                .setIssuer(issuer)
                .setAudience(audience)
                .signWith(signatureAlgorithm, signingKey);

        //添加Token过期时间
        if (TTLMillis >= 0) {
            long expMillis = nowMillis + TTLMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp).setNotBefore(now);
        }

        return builder.compact();
    }

    /**
     * 创建JWTToken
     *
     * @param loginId
     * @param params
     * @return
     */
    public static String createJWT(String loginId, Map<String, Object> params) {

        if (params == null) {
            params = new HashMap<>();
        }

        params.put(LOGIN_ID, loginId);

        //创建JWT字符串
        String jwtToken = JwtHelper.createJWT(
                params,
                jwtProperties.getClientId(),
                jwtProperties.getName(),
                jwtProperties.getExpiresSecond() * 1000,
                jwtProperties.getBase64Secret());

        return "bearer;" + jwtToken;
    }

}
